package com.qianbei.user.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.qianbei.R;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.init.GlobalConfig;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.ConstantValue;
import com.qianbei.user.BindPhoneActivity;
import com.qianbei.user.ChangeUserActivity;
import com.qianbei.user.model.UserMode;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.utils.Log;

import java.util.Map;

/**
 * Created by gml on 16/9/3.
 */
public class LoginWxActivity extends BaseActivity{

    private UMShareAPI mShareAPI;
    private String mAccessToken;
    private String mRefreshToken;
    private String mOauthUid;

    private UserMode mUserMode;

    private FrameLayout mWeChatLayout;

    public static LoginCall call;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_wx_activit);
        findViewById(R.id.login_login).setOnClickListener(this);
        findViewById(R.id.btn_login_registe).setOnClickListener(this);
        findViewById(R.id.cancel_id).setOnClickListener(this);

        mWeChatLayout = (FrameLayout) findViewById(R.id.we_chat_layout);
        mWeChatLayout.setOnClickListener(this);

        mShareAPI = UMShareAPI.get(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Intent intent =new Intent(LoginWxActivity.this,Login_regist_activity.class);
        switch (v.getId()){
            case R.id.login_login:
                intent.putExtra(ConstantValue.SELECT_TAB_KEY,true);
                startActivity(intent);
                finish();
                break;
            case R.id.btn_login_registe:
                intent.putExtra(ConstantValue.SELECT_TAB_KEY,false);
                startActivity(intent);
                finish();
                break;
            case R.id.we_chat_layout:
                mShareAPI.doOauthVerify(this, SHARE_MEDIA.WEIXIN, umAuthListener);
                mWeChatLayout.setEnabled(false);
                break;
            case R.id.cancel_id:

                finish();
                if(call!=null){
                    call.loginFail();
                }
                break;
        }
    }


    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            if (map!=null){
                Log.d("jiao","getting data "+map.toString());
                String unionId = map.get("unionid");
                mAccessToken = map.get("access_token");
                mRefreshToken = map.get("refresh_token");
                mOauthUid = map.get("openid");
                mShareAPI.getPlatformInfo(LoginWxActivity.this, share_media, platformInfoListener);

            }else{
                new MsgAlert().show(R.string.authorization_failed);
            }
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
        }
    };


    private UMAuthListener platformInfoListener = new UMAuthListener() {

        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            if (map!=null){
                Log.d("jiao","getting info data "+map.toString());
                registRequest(share_media,map);
            }else{
                new MsgAlert().show(R.string.authorization_failed);
            }
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            new MsgAlert().show(R.string.authorization_failed);
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            Log.d("onCancel info ");
        }
    };


    /**
     * 根据第三方的登录信息 注册用户
     *
     * @param share_media
     * @param map
     */
    public void registRequest(SHARE_MEDIA share_media,Map<String,String> map){

        String oauthFrom = "wb"; // 第三方登录来源，wb、qq、wx
        String oauthUnuid = "";
        String oauthNickName = "";
        String oauthFace = "";

        if (SHARE_MEDIA.SINA == share_media){
            oauthFrom = "wb";
            JSONObject jsonObject = JSON.parseObject(map.get("result"));
            oauthNickName = jsonObject.getString("name");
            oauthFace = jsonObject.getString("profile_image_url");
        }else if (SHARE_MEDIA.WEIXIN == share_media){
            oauthFrom = "wx";
            oauthUnuid = map.get("unionid");
            oauthNickName = map.get("nickname");
            oauthFace = map.get("headimgurl");
        }

        final StringBuilder builder = new StringBuilder();
        builder.append(oauthUnuid).append("/@:/");
        builder.append(mOauthUid).append("/@:/");
        builder.append(mAccessToken).append("/@:/");
        builder.append(oauthNickName).append("/@:/");
        builder.append(oauthFace).append("/@:/");
        builder.append(mRefreshToken);

        ServerControl sc = new ServerControl(OAUTH_SIGNIN_URL,
                "oauth_from", oauthFrom,		// 第三方返回的openid
                "oauth_uid", mOauthUid,			// 第三方返回的openid
                "access_token", mAccessToken,	// 第三方返回的授权token
                "refresh_token", mRefreshToken, // 第三方刷新token
                "oauth_nickname", oauthNickName,// 第三方昵称
                "oauth_face", oauthFace,	    // 第三方头像
                "oauth_unuid",oauthUnuid		// 微信登录必须，跨应用的唯一id
        );

        sc.serverListener = new ServerControl.ServerListener() {

            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    if (sr.bodyData != null){

                        mUserMode = JSON.parseObject(
                                sr.bodyData.optString("userInfo").toString(),
                                UserMode.class);

                        if (sr.bodyData.optBoolean("has_phone")){//如果已绑定则保存信息，开启服务
                            doAction();
                        }else{ //跳转到绑定手机号页面
                            Intent intent = new Intent(LoginWxActivity.this,BindPhoneActivity.class);
                            intent.putExtra(ConstantValue.WE_CHAT_INFO_KEY,builder.toString());
                            startActivityForResult(intent,1);
                        }
                    }
                }
            }
        };

        new ProgressDialog(mContext).startControl(sc,getString(R.string.login));
    }


    /**
     *
     * 下一步操作
     */
    public void doAction(){


        if (!TextUtils.isEmpty(mUserMode.user_id)) {
            saveLoginInfo(mUserMode);
        }

//        // 判断第一次登录显示 页面 登录依据
//        if (SetData.getLoginshow(mUserMode.user_id)) {
//            ActivityManagers.getInstance().finishActivity(GuideActivity.class);
//            Intent intent = new Intent(this,LogginShowActivity.class);
//            intent.putExtra("targetClass", "");
//            startActivity(intent);
//
//            SetData.setLoginshow(false, mUserMode.user_id);
//        } else {
            try {
                Class<?> targetClass = Class.forName(
                        getIntent().getStringExtra("targetClass"));
                Intent intent = new Intent(mContext, targetClass);
                startActivity(intent);

            } catch (Exception e) {
                e.printStackTrace();
            }
//        }


        finish();
    }


    /**
     * 保存用户信息
     *
     * @param bean
     */
    private void saveLoginInfo(UserMode bean) // 存储注册信息
    {

//		JpushManager.getIJpushManager().setAlias(bean.easemob_name);
//		JpushManager.getIJpushManager().setTag("jiemianmaster_register_user");

        SetData.setUserID(bean.user_id);
        SetData.setFace(bean.profile_image_url);
        SetData.setUserName(bean.name);
        SetData.sethxID(bean.easemob_name);
        SetData.sethxpass(bean.random_string);
        SetData.setUserType(bean.type);
        SetData.setCity(bean.city);
        SetData.setCountry(bean.country);
        SetData.setCareer(bean.identity);
        SetData.setIntroduction(bean.career);
        SetData.setNickName(bean.nickname);
		SetData.setUserPhone(bean.phone_number);

        GlobalConfig config = GlobalConfig.getInstance();

        if (bean.type.equals("true")) {// true 是前辈
            config.identity = "1";
            SetData.setIdentity("1");
        } else {
            SetData.setIdentity("0");
            config.identity = "0";
        }


        config.userID = bean.user_id;
        config.iconURl = bean.profile_image_url;
        config.userName = bean.name;
        config.hxID = bean.easemob_name;

        // HuanxinHelper.getInstance().login();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK){ //绑定手机成功后回调
            startActivityForResult(new Intent(this,ChangeUserActivity.class),2);
        }else if (requestCode == 2 && resultCode == RESULT_OK){ //完善用户资料后回调
            getUerInfo();
        }else{ //友盟回调
            mShareAPI.onActivityResult(requestCode,resultCode,data);
        }
    }


    /**
     * 获取用户资料
     */
    private void getUerInfo() {
        ServerControl sc = new ServerControl(Request.Method.GET, user_info + "?");
        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {

                if (sr.isContinue) {
                    mUserMode = JSON.parseObject(
                            sr.bodyData.optJSONObject("userInfo").toString(),
                            UserMode.class);
                    doAction();
                }
            }
        };
//		sc.startVolley();
        new ProgressDialog(mContext).startControl(sc);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mWeChatLayout.setEnabled(true);
    }
}
